package MyQueueDeom;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 周斌
 * Date: 2024-03-14
 * Time: 21:26
 */
public class MyQueue {
    static class ListNode {
        public int val;
        public ListNode prev;
        public ListNode next;
        public ListNode(int val) {
            this.val = val;
        }
    }
    public ListNode head;
    public ListNode last;

    //offer 入队
    public void offer(int val) {
        ListNode node = new ListNode(val);
        //1.空节点
        if(head == null) {
            head = node;
            last = node;
        } else {
            //2.不为空节点，尾插法。
            last.next = node;
            node.prev = last;
            last = node;
        }
    }
    //poll 出队
    public int poll() {
        //1.判断队是否为空
        if(isEmpty()) {
            //1.1队为空,抛出队为空的异常
           throw new QueueEmptyException("队空异常！！！！");
        } else {
            //2.队中是否只有一个元素
            int val = head.val;
            if(head.next == null) {
                //2.1只有一个元素
                head = null;
                last = null;
                return val;
            } else {
                //2.2队中不只一个元素，删头节点
                head = head.next;
                head.prev = null;
                return val;
            }
        }
    }
    public boolean isEmpty() {
        return head == null;
    }
    //peek
    public int peek() {
        //1.判断队是否为空
        if(isEmpty()) {
            //1.1队为空,抛出队为空的异常
            throw new QueueEmptyException("队空异常！！！！");
        } else {
            //1.2队不空，直接返回队头元素
             return head.val;
        }
    }
}
